﻿using Digitalmes.Domain;
using Digitalmes.Domain.Mes;
using Digitalmes.Scada.Models;
using Digitalmes.Sugar;

namespace Digitalmes.Scada.Services.Impl;

internal sealed class TakePartInService : ITakePartInService, ITransientDependency
{
    private readonly SugarRepository<ProdTransSn> _transSnRepo;
    private readonly SugarRepository<ReworkDoc> _reworkDocRepo;

    public TakePartInService(SugarRepository<ProdTransSn> transSnRepo,
        SugarRepository<ReworkDoc> reworkDocRepo)
    {
        _transSnRepo = transSnRepo;
        _reworkDocRepo = reworkDocRepo;
    }

    public async Task<HandleResult> TakePartInAsync(TakePartInInput input)
    {
        // 前提是检测产品是否是返修件且完成返修
        var transSn = await _transSnRepo.GetFirstAsync(s => (s.Sn == input.SN || s.CustomerSn == input.SN) && s.CurLineCode == input.LineCode);
        if (transSn == null)
        {
            return HandleResult.Error(ErrCode.E1402);
        }

        if (transSn.ReworkFlag is not Domain.Enums.ReworkFlagEnum.DoneAndWaitToRelaunch)
        {
            return HandleResult.Error(ErrCode.E1403);
        }

        var reworkDoc = await _reworkDocRepo.GetFirstAsync(s => s.Doc == transSn.ReworkDoc);
        if (reworkDoc == null)
        {
            return HandleResult.Error(ErrCode.E1404);
        }

        if(reworkDoc.Status is not Domain.Enums.ReworkStatusEnum.Completed)
        {
            return HandleResult.Error(ErrCode.E1405);
        }

        return HandleResult.Ok(new()
        {
            { "MES_Callback_Station", reworkDoc.RelaunchProcCode }, // 工序编号与工位编号一致
        });
    }
}
